import { indexStore } from '@/store'
import type { ConfigType, paramsType } from '../types'
export const useData = (table: any, params: any, formApi: ConfigType, props: any) => {
  const store = indexStore()
  const url: string[] = props.action?.split('/')!
  const mData = ref([])
  // 总条数
  let dataCount = ref(0)
  const selectData = () => {
    if (!props.selected || props.selected.length === 0) {
      table.value.clearSelection()
      return
    }
    props.selected.forEach((row: any) => {
      const item = mData.value.find((item: any) => item[props.currentRowKey] === row[props.currentRowKey])
      nextTick(() => {
        table.value.toggleRowSelection(item, undefined)
      })
    });
  }

  const getData = async (): Promise<void> => {
    if (props.data) {
      mData.value = props.data
      return
    }
    const mParams = {
      ...params.value,
      ...formApi.fApi.formData()
    }
    delete mParams.search
    delete mParams.clear
    // @ts-ignore
    const { data } = await store[url[0]][url[1]](mParams)
    if (data) {
      dataCount.value = data.total
      mData.value = data.list
      selectData()
    }
  }
  onMounted(() => {
    if (props.action) {
      getData()
    }
  })

  return {
    selectData,
    getData,
    mData,
    dataCount
  }
}